//
//  AlarmDetailVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/4/23.
//
// 【首页-报警通知】报警详情

import Foundation
import UIKit

class AlarmDetailVC: SubLevelViewController {
    let detailV = AlarmDetailView()

    var modal: AlarmsModal!

    init(withModal _modal: AlarmsModal) {
        super.init(nibName: nil, bundle: nil)
        self.modal = _modal
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "报警详情"
        view.backgroundColor = .bg
        
        setupUI()
        
        reloadData()
    }
    
    func reloadData() {
        // 报警详情
        API.getAlarmDetail(withParam: AlarmParam(tbId: self.modal.tbId)) { responseModel in
            DispatchQueue.main.async {
                if let modal = responseModel.model {
                    self.detailV.updateUI(withModal: modal)
                }
            }
        }
    }
    
    @objc func submitTapped() {
        self.popup.dialog(with: false, bgColor: .black.withAlphaComponent(0.65), container: {
            let padding = (ScreenWidth  - 280.0) / 2.0
            let v = ReplyPopView(frame: CGRect(x: padding, y: 24, width: 280, height: ScreenHeight))
            v.selectTextWith = { (msg) -> () in
                self.handleSubmit(withText: msg)
            }
            return v
        })
    }
    
    func handleSubmit(withText remark: String) {
        view.showToastActivity()
        API.postAlarmDetail(withParam: AlarmParam(tbId: self.modal.tbId, remark: remark)) { responseModel in
            DispatchQueue.main.async {
                self.view.hideToastActivity()
                if responseModel.errorCode == .Success {
                    NotificationCenter.default.post(name: NotiAlarm, object: nil)
                    Utils.app.window?.showToast(witMsg: responseModel.errorMessage)
                    self.navigationController?.popViewController(animated: true)
                } else {
                    self.view.showToast(witMsg: responseModel.errorMessage)
                }
            }
        }
    }
    
    // MARK: - Setup
    
    func setupUI() {
        detailV.submitBtn.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
        view.addSubview(detailV)
        detailV.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
}
